<template>
  <el-drawer
    :visible.sync="visible"
    direction="btt"
    class="operationDrawer"
    :size="601"
    :withHeader="false"
    :wrapperClosable="false"
  >
    <div v-loading="loading" element-loading-text="提交中...">
      <div class="titleWrap">
        <span class="title">{{ drawerTitle }}</span>
        <i class="el-icon-close icon" @click="closeDrawer"></i>
      </div>
      <div v-if="visible" class="myContainer">
        <DataRecord
          ref="dataRecordRef"
          :key="dataRecordKey"
          :pfTime="pfTime"
          :cfgData="cfgData"
          :recordData="recordData"
          :isEdit="isEdit"
        />
        <div v-if="!canEdit" class="mask"></div>
      </div>
      <div class="footerWrap">
        <div class="opTimeWrap">
          <span class="opTimeText">操作时间：</span>
          <DateSelection
            v-model="pfTime"
            style="margin-left: 5px; width: 200px; padding-right: 0"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm"
            :simple-op="true"
            :date-picker-show="true"
            :date-show="true"
            :no-clear="true"
            @onchange="handleChangeRecordTime"
          />
        </div>
        <div class="signWrap">
          <span class="signText">签名：</span>
          <span class="signUser">{{ user.name }}</span>
        </div>
        <div class="btnsWrap">
          <el-button class="resetBtn" @click="handleReset">清空</el-button>
          <el-button
            class="submitBtn"
            type="primary"
            :loading="loading"
            @click="handleSave"
          >
            保存
          </el-button>
          <div v-if="isLockBtns" class="mask"></div>
        </div>
        <div v-if="!canEdit" class="mask"></div>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { format } from 'date-fns'
import { cloneDeep, flatten, isEmpty, omit, pick } from 'lodash-unified'
import { nanoid } from 'nanoid'
import { computed, defineComponent, nextTick, reactive, toRefs } from 'vue'

import {
  getRecordTimeCareData,
  saveCareData
} from '@/api/manage/doc-IntensiveCareRecord'
import DateSelection from '@/components/DateSelection/indexV2.vue'
import {
  getElementFnFromInstance,
  getStoreFromInstance
} from '@/utils/instance'

import DataRecord from './DataRecord.vue'

export default defineComponent({
  name: 'OperationDrawer',
  components: {
    DateSelection,
    DataRecord
  },
  props: {
    cfgData: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update'],
  setup(props, { emit }) {
    const state = reactive({
      visible: false,
      loading: false,
      dataRecordKey: nanoid(),
      dataRecordRef: {},
      diseaseObservationKey: nanoid(),
      pfTime: '',
      originalTime: '', // 编辑的那行数据的原来的时间
      recordData: [],
      isEdit: false,
      isLockBtns: false
    })

    const store = getStoreFromInstance()
    const { $notify } = getElementFnFromInstance()

    const user = computed(() => store.getters.user)
    const patCur = computed(() => store.getters.patCur)
    const roles = computed(() => store.getters.roles)

    const drawerTitle = computed(() =>
      state.isEdit ? '编辑记录单' : '新增记录单'
    )

    /**
     * 判断是否可编辑
     */
    const canEdit = computed(() => {
      if (!state.isEdit) {
        return true
      }
      if (state.recordData.length > 0) {
        if (roles.value.includes(window.nurseLeaderRole)) {
          return true
        }
        const operatorData = state.recordData.find(
          v => v.dictValue === 'operater'
        )
        // 设备采集的记录没有操作人，需要判断
        if (operatorData && operatorData.val) {
          return operatorData.val === user.value.name
        }

        return true
      }
      return true
    })

    /**
     * 显示抽屉
     * @param {any} recordData 记录数据
     */
    function openDrawer(recordData, isEdit = true) {
      state.isEdit = isEdit
      state.pfTime = format(new Date(), 'yyyy-MM-dd HH:mm:ss')
      state.originalTime = ''

      if (recordData) {
        state.recordData = cloneDeep(recordData)

        if (isEdit) {
          const timeData = recordData.find(v => v.dictValue === 'date_value')

          if (timeData) {
            state.pfTime = timeData.val
            state.originalTime = timeData.val
          } else {
            $notify({
              title: '提醒',
              message: '记录时间缺失',
              customClass: 'superZ',
              duration: 1800
            })
          }
        }
      }

      state.visible = true
      nextTick(() => {
        if (!canEdit.value && isEdit) {
          notSelfNotify()
        }
      })
    }

    /**
     * 非本人编辑提示
     */
    function notSelfNotify() {
      $notify.warning({
        title: '提示',
        message: '非本人创建的记录，请联系签名者修改',
        customClass: 'superZ',
        duration: 1800
      })
    }

    /**
     * 关闭抽屉
     */
    function closeDrawer() {
      state.recordData = []
      state.isEdit = false
      state.visible = false
    }

    /**
     * 清空重置
     */
    function handleReset() {
      state.recordData = []
      state.dataRecordKey = nanoid()
      state.diseaseObservationKey = nanoid()
    }

    /**
     * 保存
     */
    async function handleSave() {
      state.loading = true

      const data = {
        // 观察项
        gcx: [],
        // 护理操作
        hlcz: [],
        // 护理记录
        hljl: [],
        // 出入量
        io: [],
        // 评估评分（普通）
        pg: [],
        // 评估评分（跌倒、Braden）
        vte: [],
        // 账号
        account: '',
        // 账号编号
        userId: '',
        // 操作人
        operator: '',
        // 记录时间
        recordTime: '',
        // 病人识别号
        patientIdent: '',
        // 住院号
        hospitalNumber: ''
      }

      data.account = user.value.account
      data.userId = user.value.id
      data.operator = user.value.name
      data.recordTime = new Date(state.pfTime).getTime()
      data.patientIdent = patCur.value.patientIdent
      data.hospitalNumber = patCur.value.hospitalNumber

      if (state.isEdit && state.originalTime) {
        data.originalTime = new Date(state.originalTime).getTime()
      }

      // 处理数据记录
      const { gcx, hlcz, io } = state.dataRecordRef.save()
      if (!isEmpty(gcx)) {
        const gcxData = Object.values(gcx)
          .filter(v => v.value !== undefined && String(v.value).trim() !== '')
          .map(v => ({
            ...omit(v, ['value']),
            ...pick(data, ['patientIdent', 'hospitalNumber']),
            propValue: v.value
          }))
        if (gcxData.length > 0) {
          data.gcx = gcxData
        }
      }
      if (!isEmpty(hlcz)) {
        const hlczData = Object.values(hlcz)
          .filter(v => v.value !== undefined && String(v.value).trim() !== '')
          .map(v => ({
            ...omit(v, ['value', 'id']),
            ...pick(data, ['patientIdent', 'hospitalNumber']),
            itemValue: v.value
          }))
        if (hlczData.length > 0) {
          data.hlcz = hlczData
        }
      }
      if (!isEmpty(io)) {
        let ioData = Object.values(io)
        if (ioData.length > 0) {
          ioData = flatten(ioData).map(v => ({
            ...omit(v, ['value']),
            ...pick(data, ['patientIdent', 'hospitalNumber']),
            ioValue: v.value
          }))
        }
        data.io = ioData
      }

      // 处理评估评分
      const evalItems = state.dataRecordRef.evalItems
      Object.keys(evalItems).forEach(key => {
        if (evalItems[key].type === 'yx-pgpf') {
          // 非空判断
          const evalItemData = evalItems[key].data
          if (!isEmpty(evalItemData)) {
            if (state.isEdit) {
              data.pg.push(evalItemData)
            } else {
              data.pg.push({
                ...omit(evalItemData, ['id'])
              })
            }
          }
        } else {
          // 非空判断
          const evalItemData = evalItems[key].data
          if (!isEmpty(evalItemData)) {
            if (state.isEdit) {
              data.vte.push(evalItemData)
            } else {
              data.vte.push({
                ...omit(evalItemData, ['id'])
              })
            }
          }
        }
      })
      // 处理护理记录数据
      const hljlData = {
        ...pick(data, ['patientIdent', 'hospitalNumber'])
      }
      if (
        String(hljlData.careContent).trim() !== '' &&
        hljlData.careContent !== null &&
        hljlData.careContent !== undefined
      ) {
        data.hljl.push(hljlData)
      }

      try {
        await saveCareData(data)
        closeDrawer()
        emit('update')
      } finally {
        state.loading = false
      }
    }

    /**
     * 变更操作时间需要做权限判断
     */
    function handleChangeRecordTime(val) {
      // state.isLockBtns = true
      // getRecordTimeCareData({
      //   hospitalNumber: patCur.value.hospitalNumber,
      //   patientIdent: patCur.value.patientIdent,
      //   recordTime: new Date(val).getTime()
      // }).then(({ data }) => {
      //   state.isLockBtns = false
      //   if (data && data.length > 0) {
      //     const operator = Object.keys(data[0])[0].split('@')[1]
      //     if (operator && operator !== user.value.name) {
      //       state.isLockBtns = true
      //       notSelfNotify()
      //     }
      //   }
      // })
    }

    return {
      ...toRefs(state),
      user,
      drawerTitle,
      canEdit,
      openDrawer,
      closeDrawer,
      handleReset,
      handleSave,
      handleChangeRecordTime
    }
  }
})
</script>

<style scoped lang="scss">
@import './styleVars.scss';

.operationDrawer {
  ::v-deep .el-drawer__body {
    display: flex;
    flex-flow: column nowrap;
    padding: 20px 30px;
  }

  .mask {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    z-index: 100;
  }

  .titleWrap {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      display: flex;
      align-items: center;
      font-size: 16px;
      color: #333;
      font-weight: bold;

      &::before {
        content: ' ';
        display: block;
        width: 4px;
        height: 22px;
        margin-right: 10px;
        background-color: $mainColor;
      }
    }

    .icon {
      position: relative;
      font-size: 18px;
      cursor: pointer;
      color: rgb(0 0 0 / 30%);
      z-index: 101;
    }
  }

  .myContainer {
    flex: 1;
    padding: 20px 30px 0;

    ::v-deep .el-tabs {
      .el-tabs__item {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        width: 140px;
        height: 32px;
        padding: 0;
        color: $mainColor;
        border: 1px solid $mainColor;
        border-radius: 4px 0 0 4px;
        line-height: 1;

        &:last-child {
          border-radius: 0 4px 4px 0;
        }

        &.is-active {
          color: #fff;
          background-color: $mainColor;
        }
      }

      .el-tabs__active-bar {
        display: none;
      }

      .el-tabs__nav-wrap::after {
        display: none;
      }
    }
  }

  .footerWrap {
    position: relative;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    font-size: 14px;

    .opTimeWrap {
      display: flex;
      align-items: center;

      .opTimeText {
        color: #333;
      }
    }

    .signWrap {
      display: flex;
      align-items: center;
      margin-left: 30px;

      .signText {
        color: #333;
      }

      .signUser {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 80px;
        height: 30px;
        background-color: #f9f9f9;
        border: 1px solid #dfe4ed;
      }
    }

    .btnsWrap {
      position: relative;
      margin-left: 202px;

      .resetBtn {
        color: #fff;
        background: #ccc;

        &:hover {
          border-color: unset;
        }
      }

      .submitBtn {
        background: $mainColor;

        &:hover {
          border-color: unset;
        }
      }
    }
  }
}
</style>
